//
//  AppDelegate.m
//  TestAppDelegateService
//
//  Created by yuemei on 2017/9/21.
//  Copyright © 2017年 yuemei. All rights reserved.
//

#import "GGMainAppDelegate.h"
#import <objc/runtime.h>
#import <objc/message.h>

@interface GGMainAppDelegate ()

@end

@implementation GGMainAppDelegate

//强制响应方法
-(BOOL)respondsToSelector:(SEL)aSelector{
    //判断是否可以响应方法,并筛除_objc_msgForward
    BOOL canResponds = [self methodForSelector:aSelector] != nil && [self methodForSelector:aSelector] != _objc_msgForward;
    //容错,处理不能响应状况
    if (!canResponds && [[self appDelegateMethods] containsObject:NSStringFromSelector(aSelector)]) {
        canResponds = [[GGAppServiceManager sharedAppServiceManager] proxyCanResponseToSelector:aSelector];
    }
    return canResponds;
}
    
//方法转发到相应Service
-(void)forwardInvocation:(NSInvocation *)anInvocation{
    [[GGAppServiceManager sharedAppServiceManager] proxyForwardInvocation:anInvocation];
}
    

-(NSArray<NSString *> *)appDelegateMethods{
    static NSMutableArray *methods = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       unsigned int methodCount = 0;
        //获取UIApplicationDelegate方法列表
        struct objc_method_description *methodList = protocol_copyMethodDescriptionList(@protocol(UIApplicationDelegate), NO, YES, &methodCount);
        methods = [NSMutableArray arrayWithCapacity:methodCount];
        for (int i = 0; i < methodCount; ++i) {
            struct objc_method_description method = methodList[i];
            [methods addObject:NSStringFromSelector(method.name)];
        }
        //methodList生命周期结束,释放
        free(methodList);
    });
    return methods;
}
@end
